/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cardreader;

import View.DPIViewer;
import Controller.Reader;
import java.util.List;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.TerminalFactory;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

/**
 *
 * @author giovannirojas
 */
public class AreYou {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Todo inicio bueno tiene un final feliz. 
        
        // Set default look and feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                    "Error al cargar Look And Feel: " + e.getMessage(),
                    "Error Look And Feel",
                    JOptionPane.WARNING_MESSAGE);
        }
        
        // Verifico que exista un lector de DPI 
        // Get the list of terminals
        CardTerminal terminal = null;
        try {
            TerminalFactory factory = TerminalFactory.getDefault();
            terminal = pickTerminalGUI(null, factory.terminals().list());

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                    "No hay un lector de DPI, el programa se cerrará.",
                    "No encuentra lector",
                    JOptionPane.ERROR_MESSAGE);
            
            System.exit(1);
        }
        
        
        
        
        // Muestra la primera ventana donde empezara la lectura de DPI
        
        DPIViewer va = new DPIViewer();
        va.setLocationRelativeTo(null);
        va.setVisible(true);
        
        // Create reader and add GUI as the listener
        Reader reader = new Reader(terminal);
        reader.addCardListener(va);
        
        
        
    }
    
    
    public static CardTerminal pickTerminalGUI(JFrame frame, List<CardTerminal> terminals)
    {
        if(terminals.size() == 1) return terminals.get(0);
        
        CardTerminal terminal = (CardTerminal)JOptionPane.showInputDialog(frame,
                                        "Seleccione Lector a usar.",
                                        "Selección Lector",
                                        JOptionPane.PLAIN_MESSAGE,
                                        null,
                                        terminals.toArray(),
                                        terminals.get(0));

        // Cancel clicked
        if(terminal == null) System.exit(1);

        return terminal;
    }
}
